const Task = require('../models/task')
const Taskaudit = require('../models/taskaudit')
const Category = require('../models/category')

module.exports = {
    // async setparentid(num,id,data){
    //     data.unshift(id)
    //     if (num > 0) {
    //         let {parentId} = await Task.findById(id).lean()
    //         parentId = mongoose.Types.ObjectId(parentId).toString()
    //         num--;
    //         await arguments.callee(num, parentId, data)
    //     } else {
    //         return data
    //     }  
    // }

    async hanleTask(data, arr) {
        for (let i = 0; i < data.length; i++) {
            let data1 = await Task.find({
                parentId: data[i]._id
            }).populate('creator worker')
            .lean()
            if (data1.length > 0) {
                data[i].children = data1
                let data2 = data[i].children
                await arguments.callee(data2, arr)
            }
        }
        arr.push(data)
    },
    async handleCate(data,arr){
        for (let i = 0; i < data.length; i++) {
            let cate = await Category.find({
                    parentId: data[i]._id
                }).lean()
            if (cate.length > 0) {
                data[i].children = cate
                let data2 = data[i].children
                await arguments.callee(data2, arr)
            }
        }
        arr.push(data)
    },

    async deletaTask(parentId) {
        let tasks = await Task.find({
            parentId: parentId
        })
        let datas = await Task.deleteMany({
            parentId: parentId
        })

        if (datas.deletedCount > 0 && tasks.length > 0) {

            for (let i in tasks) {
                await Taskaudit.deleteMany({
                    taskId: tasks[i]._id
                })
                await arguments.callee(tasks[i]._id)
            }

        }
    },

    // 计算进度
    /**
     * parentId 父级id
     */
    //计算进度
    async countProcess(parentId) {
        //判断是否存在父级
        if (parentId) {
            //查询任务
            let parent = await Task.findById(parentId).lean()
            //查询子任务(数组)
            let sons = await Task.find({
                parentId: parent._id
            })
            //所有子任务的进度之和
            let sum = 0
            for (let i in sons) {
                sum += parseInt(sons[i].process)
            }
            //子任务数量
            let quantity = sons.length
            // console.log(sum);
            parent.process = parseInt(sum / quantity)
            await Task.findByIdAndUpdate(parent._id, parent)

            await arguments.callee(parent.parentId)
        }
    },

    huanTime(time) {
        let hTime = new Date(time)
        let resTime = new Date(hTime.getTime() + (8 * 60 * 60 * 1000))
        return resTime
    }
}